import logging
import os
import time
from datetime import datetime

import requests
import asyncio
import websockets
import json

# WebSocket 服务器地址
WEBSOCKET_URL = "ws://182.43.109.40:5000"

# Flask 上传接口地址
UPLOAD_URL = "http://182.43.109.40:5001/create/upload"

async def send_message(message):
    """发送消息到 WebSocket 服务器"""
    async with websockets.connect(WEBSOCKET_URL) as websocket:
        await websocket.send(json.dumps(message))
        logging.info(f"Message sent to WebSocket: {message}")

def upload_image(image_path):
    """
    上传图片到 Flask 服务
    :param image_path: 图片的本地路径
    :return: 服务器返回的响应
    """
    try:
        # 打开图片文件
        with open(image_path, 'rb') as image_file:
            # 准备文件字典
            files = {'file': (os.path.basename(image_path), image_file, 'image/jpeg')}

            # 发送 POST 请求
            response = requests.post(UPLOAD_URL, files=files)

            # 打印响应内容
            print("Server response:", response.json())

            # 如果上传成功，发送 WebSocket 消息
            if response.status_code == 200:
                message = {
                    "type": "image_uploaded",
                    "path": response.json().get("file_path"),
                    "timestamp": datetime.now().isoformat()
                }
                asyncio.run(send_message(message))
            else:
                print("Upload failed.")
    except Exception as e:
        print(f"Error during upload: {e}")

while True:
    # 图片路径（替换为你的图片路径）
    image_path = "C:\\Users\\Administrator\\Desktop\\目录总览\\自己的图片\\background.jpg"
    # 调用上传函数
    upload_image(image_path)
    print("1")
